Page({
  data: {
    imageSrc: '', // 用于存储选择的图片的临时路径
    canvasWidth: 300, // Canvas的宽度
    canvasHeight: 300, // Canvas的高度
    tempFilePaths: [], // 用于存储所有区块的临时路径
  },
  chooseImage: function () {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePath = res.tempFilePaths[0];

        wx.cropImage({
          src: tempFilePath, // 图片路径
          cropScale: '1:1', // 裁剪比例
          success: function (res) {
            var tempFilePathAfterCrop = res.tempFilePath;
            that.setData({
              imageSrc: tempFilePathAfterCrop
            });
            // 将图片显示在canvas上
            that.drawImageOnCanvas(tempFilePathAfterCrop);
          }
        })

      }
    });
  },
  drawImageOnCanvas: function (imageSrc) {
    const ctx = wx.createCanvasContext('myCanvas', this);
    ctx.drawImage(imageSrc, 0, 0, this.data.canvasWidth, this.data.canvasHeight);
    ctx.draw();
  },
  saveImage: function () {
    const that = this;
    const width = that.data.canvasWidth;
    const height = that.data.canvasHeight;
    const blockSizeX = Math.floor(width / 3);
    const blockSizeY = Math.floor(height / 3);

    let savedCount = 0; // 已保存区块的数量
    const maxSaveCount = 9; // 需要保存的区块总数

    // 九宫格裁剪
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < 3; j++) {
        const x = blockSizeX * j;
        const y = blockSizeY * i;
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          x,
          y,
          width: blockSizeX,
          height: blockSizeY,
          success(res) {
            savedCount++; // 保存成功的区块数量加1
            that.setData({
              // 存储所有区块的临时路径
              tempFilePaths: that.data.tempFilePaths.concat(res.tempFilePath)
            });

            if (savedCount === maxSaveCount) {
              // 当所有区块都保存成功后，保存到相册
              that.saveTempFilesToAlbum();
            }
          },
          fail(err) {
            console.error('Canvas转图片失败', err);
          }
        }, this);
      }
    }
  },
  saveTempFilesToAlbum: function () {
    const that = this;
    const tempFilePaths = that.data.tempFilePaths;
    if (tempFilePaths.length === 0) {
      wx.showToast({
        title: '没有图片可保存',
        icon: 'none',
      });
      return;
    }

    tempFilePaths.forEach((filePath, index) => {
      wx.saveImageToPhotosAlbum({
        filePath: filePath,
        success(res) {
          console.log(`第 ${index + 1} 张图片保存成功`);
          if (index === tempFilePaths.length - 1) {
            // 如果是最后一张图片，提示用户所有图片都已保存
            wx.showToast({
              title: '所有图片保存成功',
            });
            // 清空临时路径数组
            that.setData({
              tempFilePaths: [],
            });
          }
        },
        fail(err) {
          console.error(`第 ${index + 1} 张图片保存失败`, err);
        }
      });
    });
  }
});